/**
 * 
 */
package org.jenkon.commons.collection;

import java.util.Collection;

import org.jenkon.commons.collection.decorator.CollectionDecorator;
import org.jenkon.commons.lang.utils.ClassUtils;

/**
 * {@link CollectionDecorator} implementation, to merge many collections to only one
 * {@link Collection}.
 * 
 * @author Jens Konopka
 * 
 * @param <E> the type of value
 */
public class MergableCollection<E> extends CollectionDecorator<E> {

	/**
	 * @param decorator the decorating {@link Collection}
	 */
	public MergableCollection(final Collection<E> decorator) {
		super(decorator);
	}

	/**
	 * Merge this with the array with {@link Collection} objects to only one {@link Collection}.
	 * Loop over all collections and her entries and check of the value does exist in this. If the
	 * value doesn't exist in this, then put the entry to result {@link Collection}.
	 * 
	 * @param collections array of {@link Collection} objects to merge.
	 * @return {@link Collection} with the result of all.
	 */
	public Collection<E> merge(@SuppressWarnings("unchecked") final Collection<E>... collections) {
		final Collection<E> results = ClassUtils.newInstance(decorator);
		results.addAll(decorator);
		for (final Collection<E> collection : collections) {
			for (final E value : collection) {
				if (!results.contains(value)) {
					results.add(value);
				}
			}
		}
		return results;
	}
}
